/**
 *
 */
package com.joint.cloud.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;


public class MD5Util {

    private static final Logger s_logger = LoggerFactory.getLogger(MD5Util.class);

    private static final String MD5_ALGORITHM = "MD5";

    private static final int HEX_NUM = 0xff;

    /**
     * md5加密
     *
     * @param str
     * @return
     * @author wangyzh
     * @date 2012-12-7 下午12:54:02
     */
    public static String md5Encode(String str) {
        if (str == null) {
            s_logger.warn("String is null for md5 encoder.");
            return null;
        }
        try {
            MessageDigest mdEncoder = MessageDigest.getInstance(MD5_ALGORITHM);
            mdEncoder.update(str.getBytes());
            byte[] bytes = mdEncoder.digest();
            return convertToHEX(bytes);
        } catch (NoSuchAlgorithmException e) {
            s_logger.warn("Failed to encode string . There is no such algorithm.", e);
            return null;
        }
    }

    /**
     * 二进制转换成十六进制
     *
     * @param bytes
     * @return
     * @author wangyzh
     * @date 2012-12-7 下午12:58:26
     */
    private static String convertToHEX(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        StringBuffer stringBuilder = new StringBuffer();
        for (byte b : bytes) {
            int value = b & HEX_NUM;
            if (value < 16) {
                stringBuilder.append(0);
            }
            stringBuilder.append(Integer.toHexString(value));
        }
        return stringBuilder.toString();
    }

    public static String genMD5(List<String> stringList){
        try {
            StringBuffer sb = new StringBuffer();
            for (String s : stringList) {
                sb.append(s);
            }
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sb.toString().getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            String result = buf.toString();
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
